#pragma once

#include "base_types.h"
#include "poller.h"
#include "Packet.h"

// Decoder interface
class ICC_Decoder {
public:
    ICC_Decoder() = default;
    virtual ~ICC_Decoder() = default;
    
    // Parse packet data
    virtual int ParsePacket(char* data, int len, CCSocketHandler* handle, CWspack* wspack) = 0;
    
    // Reset decoder state
    virtual void Reset() = 0;
    
    // Check if packet is complete
    virtual bool IsComplete() const = 0;
    
    // Get parsed packet
    virtual std::unique_ptr<CCPacketBase> GetPacket() = 0;
};

// TCP handler interface
class ICC_TCP_Handler {
public:
    ICC_TCP_Handler() = default;
    virtual ~ICC_TCP_Handler() = default;
    
    // Handle new connection
    virtual int OnConnected(int fd, struct sockaddr_in* peer) = 0;
    
    // Handle connection close
    virtual int OnClosed(int fd) = 0;
    
    // Handle connection timeout
    virtual int OnTimeout(int fd) = 0;
};

// Socket handler base class
class CCSocketHandler : public CPollerObject {
public:
    CCSocketHandler();
    virtual ~CCSocketHandler();
    
    // Initialize handler
    virtual int Init();
    
    // Socket event handlers
    virtual int InputNotify() override;
    virtual int OutputNotify() override;
    virtual int HangupNotify() override;
    
    // Connection event handlers
    virtual int OnConnected();
    virtual int OnClose();
    virtual int OnTimeout();
    
    // Send data
    virtual int Send(CCPacketBase* packet);
    virtual int Send(const char* data, size_t size);
    
    // Get connection type
    virtual connType getConnType() = 0;
    
    // Get handler ID
    virtual uint32_t GetHandlerId() const { return handler_id; }
    
    // Set handler ID
    virtual void SetHandlerId(uint32_t id) { handler_id = id; }
    
    // Get decoder
    virtual ICC_Decoder* GetDecoder() { return decoder.get(); }
    
    // Set decoder
    virtual void SetDecoder(std::unique_ptr<ICC_Decoder> dec) { decoder = std::move(dec); }
    
    // Set data protocol type
    virtual void setDataProtocol(int protocol) { data_protocol = protocol; }
    
    // Get data protocol type
    virtual int getDataProtocol() const { return data_protocol; }
    
protected:
    // Create decoder (override in derived classes)
    virtual ICC_Decoder* CreateDecoder();
    
    // Handle received data
    virtual int HandleData(const char* data, size_t size);
    
    // Handle packet complete
    virtual int OnPacketComplete(CCPacketBase* packet);
    
protected:
    uint32_t handler_id;
    std::unique_ptr<ICC_Decoder> decoder;
    CWspack wspack;
    bool connected;
    char recv_buffer[8192];
    size_t recv_buffer_size;
    int data_protocol;
};